﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Configuration;

public partial class Checkout : System.Web.UI.Page
{
    ShopDataContext dc = new ShopDataContext();
    BankService bk = new BankService();
    AccountBank ac;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            if (Session["MyCart"] != null)
            {
                Basket b = Session["MyCart"] as Basket;
                ListView1.DataSource = b.Items;
                ListView1.DataBind();
            }
        }

        if (Session["MyCart"] != null)
        {

            //Basket b = Session["MyCart"] as Basket;
            //b.Add(new BasketItem
            //{
            //    ProductCode = dc.Products.FirstOrDefault(p => p.pId == 1).pProductCode,
            //    Price = Convert.ToInt32(dc.Products.FirstOrDefault(p => p.pId == 1).pPrice),
            //    Quantity = 1
            //});

            //Profile.MyCart = b;

            if (!Page.User.Identity.IsAuthenticated)
            {
                //Response.Redirect("Login.aspx");
                FormsAuthentication.RedirectToLoginPage();
            }
            else
            {
                MultiView1.ActiveViewIndex = 0;
            }

        }

        //        MultiView1.ActiveViewIndex = 0;
        else
        {
            Response.Redirect("Error.aspx");
        }

    }
    protected void btnNext_Click(object sender, EventArgs e)
    {
        if (ddlTypePayment.SelectedValue == "2")
            MultiView1.ActiveViewIndex = 1;
        else
            MultiView1.ActiveViewIndex = 2;
    }
    protected void btnNext2_Click(object sender, EventArgs e)
    {
        ac =  bk.Validate(txtAccNumber.Text, txtPIN.Text);
        if (ac != null)
        {
            MultiView1.ActiveViewIndex = 2;
        }
        else
        {
            lblMessageAcc.Text = "Worng Account Number and Pin";
            MultiView1.ActiveViewIndex = 1;
        }

    }
    protected void chkCheckout_Click(object sender, EventArgs e)
    {
        MultiView1.ActiveViewIndex = 3;
    }
    protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("add"))
        {
            Label l = e.Item.Controls[0].FindControl("lblCode") as Label;
            TextBox t = e.Item.Controls[0].FindControl("txtQuantity") as TextBox;
            Basket b = Session["MyCart"] as Basket;
            b.Items.FirstOrDefault(i => i.ProductCode.Equals(l.Text)).Quantity = Convert.ToInt32(t.Text);
            Session["MyCart"] = b;
            MultiView1.ActiveViewIndex = 3;
        }
        if (e.CommandName.Equals("123"))
        {
            Label l = e.Item.Controls[0].FindControl("lblCode") as Label;
            Basket b1 = Session["MyCart"] as Basket;
            b1.Remove(b1.Items.FirstOrDefault(i => i.ProductCode.Equals(l.Text)));
            ListView1.DataSource = b1.Items;
            ListView1.DataBind();
            Session["MyCart"] = b1;
            MultiView1.ActiveViewIndex = 3;
        }
    }
    protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        Label l = e.Item.FindControl("lblName") as Label;
        l.Text = dc.Products.FirstOrDefault(p => p.pProductCode == l.Text).pName;

    }

    public string IdentityCode()
    {
        string code = "";
        code =  ddlTypePayment.SelectedValue;
        Basket b = Session["MyCart"] as Basket;
        foreach (var item in b.Items)
        {
            code = code + item.ProductCode;
            break;
        }
        Order o = (from o1 in dc.Orders
                  orderby o1.oId descending
                  select o1).FirstOrDefault();
        if (o != null)
        {
            int oCode = Convert.ToInt32(o.oOrderCode.Substring(o.oOrderCode.Length - 8))+1;
            string str = oCode.ToString();
            switch(str.Length)
            {
                case 1: str ="0000000" + str;
                    break;
                case 2: str = "000000" + str;
                    break;
                case 3: str = "00000" + str;
                    break;
                case 4: str = "0000" + str;
                    break;
                case 5: str = "000" + str;
                    break;
                case 6: str = "00" + str;
                    break;
                case 7: str = "0" + str;
                    break;
            }
            code = code + str;
        }
        else
        {
            code = code + "00000001";
        }
        return code;
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        MembershipUser user = Membership.GetUser(Page.User.Identity.Name);
        Order o = new Order();
        o.oOrderCode = IdentityCode();
        o.oUser = user.ProviderUserKey.ToString();
        o.oDate = DateTime.Now;
        o.oTypePayment = int.Parse(ddlTypePayment.SelectedValue);
        o.oStatus = 0;

        dc.Orders.InsertOnSubmit(o);

        dc.SubmitChanges();

        Basket b = Session["MyCart"] as Basket;
        int sum = 0;
        if (b.Items.Count != 0)
        {
            foreach (var item in b.Items)
            {
                OrderDetail od = new OrderDetail();
                od.oId = o.oId;
                od.oQuantity = item.Quantity;
                od.pId = dc.Products.FirstOrDefault(p => p.pProductCode == item.ProductCode).pId;
                od.oPrice = item.Price;
                dc.OrderDetails.InsertOnSubmit(od);
                sum+=Convert.ToInt32(od.oPrice);
            }
            dc.SubmitChanges();

            AddressDelivery add = new AddressDelivery();
            add.adAddressDetail = txtAddress.Text;
            add.adActive = true;

            dc.AddressDeliveries.InsertOnSubmit(add);

            dc.SubmitChanges();
            
            if(ddlTypePayment.SelectedValue == "2")
            {
                string str = ConfigurationManager.AppSettings["adminAccBank"].ToString();
                bk.Transfer(txtAccNumber.Text,str , sum);
            }
            Session["MyCart"] = null;
            Response.Redirect("Default.aspx");
        }
        else
        {

        }

    }
}